import datetime
import os
import sys
from pathlib import Path

from mars.utils.common import read_yaml_config

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# 通过配置文件增加host,以便部署
yaml_cfg = read_yaml_config(os.path.join(BASE_DIR, "config/host.yml"))

ALLOWED_HOSTS = ["127.0.0.1"] + yaml_cfg.get("host", [])
# 追加系统导包路径
# sys.path.insert(0, os.path.join(BASE_DIR, "apps"))

# 私钥文件路径
CERT_ROOT = os.path.join(BASE_DIR, "cert")
# if yaml_cfg.get('debug',False):
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static_files"),)
# else:
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = "/static/"

MEDIA_ROOT = os.path.join(BASE_DIR, "media")  # 注意此处不要写成列表或元组的形式
# 配置 MEDIA_URL 作为公用 URL，指向上传文件的基本路径
MEDIA_URL = "/media/"

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-26$)sl9(e8&tk-4z@0ip5cbqoa=8(lk_uj48cauz^z8%hz!s9x"


# Application definition
INSTALLED_APPS = [
    "daphne",
    "simpleui",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "rest_framework",  # DRF
    "rest_framework_simplejwt",
    "django_filters",
    "channels",
    "django_apscheduler",
    "mars.apps.scheduler.apps.SchedulerConfig",  # 定时任务模块
    "mars.apps.realtimelog.apps.RealtimelogConfig",  # 实时日志模块
    "mars.apps.systems.apps.SystemsConfig",  # 系统管理模块
    "mars.apps.users.apps.UsersConfig",  # 用户模块
    "mars.apps.oauth.apps.OauthConfig",  # 认证登录模块
    "mars.apps.photo.apps.PhotoConfig",  # 证件照模块
    "mars.apps.orders.apps.OrdersConfig",  # 订单模块
    "mars.apps.advertisement.apps.AdvertisementConfig",  # 广告模块
    "mars.apps.aliyun.apps.AliyunConfig",  # 阿里云api
    "mars.apps.wechat.apps.WechatConfig",  # 微信模块
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "mars.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(BASE_DIR, "templates")],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "mars.wsgi.application"
ASGI_APPLICATION = "mars.asgi.application"

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = "zh-Hans"

TIME_ZONE = "Asia/Shanghai"

USE_I18N = True

USE_TZ = False


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = "static/"

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# 日志
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,  # 是否禁用已存在的日志器
    "formatters": {  # 日志信息显示格式
        "verbose": {
            "format": "{levelname} {asctime} {module} {lineno:d} {message}",
            "style": "{",
        },
        "simple": {
            "format": "{levelname} {module} {lineno:d} {message}",
            "style": "{",
        },
    },
    "filters": {  # 对日志进行过滤
        "require_debug_true": {  # django在debug模式下才输出日志
            "()": "django.utils.log.RequireDebugTrue",
        },
    },
    "handlers": {  # 日志处理方法
        "console": {  # 向终端输出日志
            "level": "INFO",
            "filters": ["require_debug_true"],
            "class": "logging.StreamHandler",
            "formatter": "simple",
        },
        "file": {  # 向文件输出日志
            "level": "INFO",
            "class": "logging.handlers.RotatingFileHandler",
            "filename": os.path.join(os.path.dirname(BASE_DIR), "logs/mars.log"),
            "maxBytes": 300 * 1024 * 1024,
            "backupCount": 10,
            "formatter": "verbose",
            "encoding": "utf-8",
        },
    },
    "loggers": {  # 日志器
        "django": {
            "handlers": ["console", "file"],  # 同时向终端和文件中输出日志
            "propagate": True,  # 是否继续传递日志信息
            "level": "DEBUG",  # 日志器接收的最低日志级别
        }
    },
}


# 修改django认证系统的用户模型类
AUTH_USER_MODEL = "users.User"


# simpleUI设置
# 隐藏右侧SimpleUI广告链接和使用分析
SIMPLEUI_HOME_INFO = False
SIMPLEUI_ANALYSIS = False
# 设置默认主题，指向主题css文件名。Element-ui风格
# SIMPLEUI_DEFAULT_THEME = "element.css"
# 修改首页设置, 指向新创建的控制面板
SIMPLEUI_HOME_PAGE = "/dashboard/"
SIMPLEUI_HOME_TITLE = "控制面板!"
SIMPLEUI_HOME_ICON = "fa fa-eye"
SIMPLEUI_LOGO = "/static/image/logo.png"
SIMPLEUI_LOGIN_PARTICLES = False
SIMPLEUI_CONFIG = {
    # 是否使用系统默认菜单，自定义菜单时建议关闭。
    "system_keep": False,
    "dynamic": True,
    # 用于菜单排序和过滤, 不填此字段为默认排序和全部显示。空列表[] 为全部不显示.
    "menu_display": [
        "系统设置",
        "证件照管理",
        "广告设置",
        "用户管理",
        "统计数据",
        "认证和授权",
    ],
    "menus": [
        {
            # 自2021.02.01+ 支持多级菜单，models 为子菜单名
            "name": "系统设置",
            "icon": "fa fa-th-large",
            # 二级菜单
            "models": [
                {
                    "name": "功能定价",
                    "icon": "fa fa-jpy",
                    "url": "/admin/systems/funcprice/",
                },
                {
                    "name": "微信设置",
                    "models": [
                        {
                            "name": "小程序设置",
                            "icon": "fa fa-commenting",
                            "url": "/admin/systems/miniappconfig",
                        },
                        {
                            "name": "服务端设置",
                            "icon": "fa fa-server",
                            "url": "/admin/systems/wechatconfig",
                        },
                    ],
                },
                {
                    "name": "阿里云设置",
                    "icon": "fa fa-cloud",
                    "url": "/admin/systems/aliconfig",
                },
                {
                    "name": "数据库备份",
                    "icon": "fa fa-database",
                    "url": "/admin/systems/dbmanager",
                },
            ],
        },
        {
            "name": "证件照管理",
            "icon": "fa fa-id-card",
            "models": [
                {"name": "类型", "icon": "fa fa-list-ol", "url": "/admin/photo/category"},
                {"name": "尺寸", "icon": "fa fa-retweet", "url": "/admin/photo/idphoto"},
                {
                    "name": "背景色",
                    "icon": "fa fa-square",
                    "url": "/admin/photo/background",
                },
            ],
        },
        {
            "name": "广告设置",
            "models": [
                {
                    "name": "广告设置",
                    "url": "/admin/advertisement/advertisement",
                }
            ],
        },
        {
            "name": "用户管理",
            "icon": "fa fa-users",
            "models": [
                {"name": "用户", "icon": "fa fa-user", "url": "/admin/users/user"}
            ],
        },
        {
            "name": "统计数据",
            "models": [
                {
                    "name": "订单",
                    "url": "/admin/orders/order",
                }
            ],
        },
    ],
}
SIMPLEUI_ICON = {
    "用户管理": "fa fa-users",
    "用户": "fa fa-user",
    "证件照管理": "fa fa-id-card",
    "尺寸": "fa fa-retweet",
    "背景颜色": "fa fa-square",
    "类型": "fa fa-list-ol",
    "小程序后端配置": "fa fa-comments",
    "功能定价": "fa fa-jpy",
}


# DRF配置
REST_FRAMEWORK = {
    # 认证
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework.authentication.SessionAuthentication",  # session认证
        "rest_framework.authentication.BasicAuthentication",  # 基本认证
        "mars.apps.oauth.utils.JwtAuthentication",  # 将自定义token放到最后验证 
    ),
    "DEFAULT_FILTER_BACKENDS": ("django_filters.rest_framework.DjangoFilterBackend",),
    # 权限控制
    "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",),
    "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.AllowAny",),
    # 异常处理
    "EXCEPTION_HANDLER": "mars.utils.exceptions.exc_handlers.exception_handler",
    "DEFAULT_RENDERER_CLASSES": (
        "mars.utils.custome_renderer.CustomRenderer",
        "rest_framework.renderers.BrowsableAPIRenderer",
    ),
}
# 自定义配置

SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": datetime.timedelta(days=1),
    "REFRESH_TOKEN_LIFETIME": datetime.timedelta(days=3),
    "AUTH_HEADER_TYPES": ("JWT",),
}

# Database
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "HOST": yaml_cfg.get("database", {}).get(
            "host", "db"
        ),  # "106.75.30.7",  # 数据库主机
        "PORT": yaml_cfg.get("database", {}).get("port", 3306),  # 数据库端口
        "USER": yaml_cfg.get("database", {}).get("user", ""),  # 数据库用户名
        "PASSWORD": yaml_cfg.get("database", {}).get("password", ""),  # 数据库密码
        "NAME": yaml_cfg.get("database", {}).get("db", "mars"),  # 数据库名称
    }
}
SECURE_CROSS_ORIGIN_OPENER_POLICY = "None"
CSRF_TRUSTED_ORIGINS = [
    "http://" + i if i.find("http://") == -1 and i.find("https://") == -1 else i
    for i in yaml_cfg.get("host", [])
] + [
    "https://" + i
    for i in yaml_cfg.get("host", [])
    if i.find("http://") == -1 and i.find("https://") == -1
]
DEBUG = yaml_cfg.get("debug", False)
MP_VER = "1.0.0"
